//内网测试图片上传地址
const imgUrl="http://192.168.2.12/images/";

/**
 * [json转化为数据字符]
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
export const paramType = data => {
    let arr = [];
    for (var name in data) {
        arr.push(name + '=' + data[name]);
    }
    arr.push('time=' + new Date().getTime());
    return arr.join('&');
}
/**
 * URL获取关键字内容
 * @param keyName
 * @param newStr
 * @returns {string}
 */
export const urlKey = (keyName, newStr = location.href) => {
    let reg = new RegExp(keyName + '=([^&]*)(&|$)', 'i');
    let keyValue = reg.test(newStr) ?
        reg.exec(newStr)[1] :
        '';
    return keyValue.replace(/\s/ig, '');
};
/**
 * Ajax请求
 */
export const ajax = (config = {}) => {
    if (config.async == undefined)
        config.async = true;
    let request = new XMLHttpRequest();
    let sign = config.url.indexOf('?') > -1 ?
        '&' :
        '?';
    let data = HttpService.formatParams(config.data);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var status = request.status;
            if (status == 200) {
                config.success(request.responseText);
            } else {
                config.fail(status);
                Tips('连接网络失败');
            }
        }
    };

    if (config.type == 'post') {
        request.open('POST', config.url, config.async);
        request.send(config.data);
    } else {
        request.open('GET', config.url + sign + paramType(config.data), config.async);
        request.send(null);
    }
};


/**
 * Tips提示消息
 * @param msg
 * @param duration
 * @constructor
 */
export let msgTout = null;
export const Tips = (msg = '未获取到信息', duration = 3) => {
    let msgObj = document.querySelector('.tips'),
        msgSpan = msgObj ?
        msgObj.querySelector('span') :
        null;
    if (msgObj == undefined) {
        msgObj = document.createElement('div');
        msgSpan = document.createElement('span');
        msgObj.appendChild(msgSpan);
        msgObj.className = 'tips';
        document.body.appendChild(msgObj);
    }
    msgSpan.innerHTML = msg;
    msgObj.style.bottom = '10rem';
    msgObj.style.display = 'block';
    setTimeout(() => {
        msgObj.style.bottom = '11rem';
        msgObj.style.opacity = '1';
    }, 10);
    clearTimeout(msgTout);
    if (duration == 0)
        return;
    if (msg == '关闭')
        msgObj.style.display = 'none';
    msgTout = setTimeout(function() {
        msgObj.style.display = 'none';
        msgObj.style.bottom = '10rem';
        msgObj.style.opacity = '0';
    }, duration * 1000);
};


/**
 * 上传图片
 * @param file input获取的file值
 * @returns {*} 服务器返回的img的url
 */
export const uploadImgs=file=>{
    let data = new FormData();
    let Url;
    data.append('file', file);
    $.ajax({
        url: "upload/uploadPic?token=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzc4MSIsImlhdCI6MTUwNjE0ODI0NSwiaXNzIjoiMTUyMDgyMDY4MDgiLCJhdWQiOiJndWFyZGlhbiJ9.YpztKWHAVdEXwzdELZLSsvF5M4tuR-rTMa5oYYVOmjA",
        type: "post",
        async: false,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (res) {
            Url= res
        }
    });
    return imgUrl + Url
};

/**
 * 获取图片信息
 * @param element
 * @param callback
 * @callback imgInfo
 */
export const getImgInfo = (element,callback)=> {
    let imgInfo = {
        width: 0,
        height: 0,
        size: 0,
        src: ''
    };
    let input = document.getElementById(element);
    if(input.files){
        //读取图片数据
        let f = input.files[0];
        let reader = new FileReader();
        reader.onload = function (e) {
            let data = e.target.result;
            //加载图片获取图片真实宽度和高度
            let image = new Image();
            imgInfo.src = data;
            image.src= data;
            image.onload=function(){
                imgInfo.width = image.width;
                imgInfo.height = image.height;
                imgInfo.size = f.size;
                callback(imgInfo);
            };
        };
        reader.readAsDataURL(f);
    }else{
        let image = new Image();
        imgInfo.src = input.value;
        image.src = input.value;
        image.onload =function(){
            imgInfo.width = image.width;
            imgInfo.height = image.height;
            imgInfo.size = image.fileSize;
            callback(imgInfo);
        };
    }
};
/**
 * 获取当前时间
 * @param format :yyyy-MM-dd HH:MM:SS yyyy-MM-dd MM-dd HH:MM:SS HH:MM MM:SS
 * @return newDate(yyyy-MM-dd HH:MM:SS)
 */
export const getNowFormatDate = (format = 'yyyy-MM-dd HH:MM:SS',time = new Date())=> {
    let date = new Date(time);
    let seperator1 = "-";
    let seperator2 = ":";
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    let getHours = date.getHours();
    let getMinutes = date.getMinutes();
    let getSeconds = date.getSeconds();

    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (getHours >= 0 && getHours <= 9) {
        getHours = "0" + getHours;
    }
    if (getMinutes >= 0 && getMinutes <= 9) {
        getMinutes = "0" + getMinutes;
    }
    if (getSeconds >= 0 && getSeconds <= 9) {
        getSeconds = "0" + getSeconds;
    }

    let currentdate = '';
    switch (format){
        case 'MM-dd':
            currentdate = month + seperator1 + strDate;
            break;
        case 'yyyy-MM':
            currentdate = date.getFullYear() + seperator1 + month;
            break;
        case 'yyyy-MM-dd':
            currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
            break;
        case 'HH:MM':
            currentdate = getHours + seperator2 + getMinutes;
            break;
        case 'HH:MM:SS':
            currentdate = getHours + seperator2 + getMinutes + seperator2 + getSeconds;
            break;
        case 'MM:SS':
            currentdate = getMinutes + seperator2 + getSeconds;
            break;
        default :
            currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + getHours + seperator2 + getMinutes + seperator2 + getSeconds;
            break;
    }
    return currentdate;
};

/**
 * 获取当前时间
 * 获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS”
 */
export const getFormatDate = ()=>{
    let date = new Date();
    let seperator1 = "-";
    let seperator2 = ":";
    let hours = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(hours < 10){
        hours = "0"+hours;
    }
    if(min < 10){
        min = "0"+min;
    }
    if(sec < 10){
        sec = "0"+sec;
    }
    let currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + hours + seperator2 + min
        + seperator2 + sec;
    return currentdate;
};